package org.abratuhi.kvngroupware.model;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import org.abratuhi.kvngroupware.gui.GUIChatroom;
import org.jdom.Element;

public class Chatroom {
	
	String id = new String();
	ArrayList<User> members = new ArrayList<User>();
	
	GUIChatroom gui;
	
	public Chatroom(){
		
	}
	public Chatroom(String id){
		setId(id);
	}
	
	public String getId(){
		return this.id;
	}
	public /*synchronized*/ ArrayList<User> getMembers(){
		return this.members;
	}
	
	public GUIChatroom getGUI(){
		return this.gui;
	}
	
	void setId(String id){
		this.id = id;
	}
	public void setGUI(GUIChatroom gui){
		this.gui = gui;
	}
	
	public synchronized String addMember(User u){
		String returnMessage = "";
		if(this.getMembers().contains(u.getId())){
			returnMessage = "Team already contains member with id:\t"+u.getId()+"."+"\n";
		}
		else{
			this.getMembers().add(u);
		}
		return returnMessage;
	}
	
	public synchronized String removeMember(User u){
		String returnMessage = "";
		if(!this.getMembers().contains(u)){
			returnMessage = "Team doesn't contain member with id:\t"+u.getId()+"."+"\n";
		}
		else{
			this.getMembers().remove(u);
		}
		return returnMessage;
	}
	
	public synchronized String removeMember(String id){
		String returnMessage = "";
		boolean found = false;
		for(int i=0; i<members.size(); i++){
			if(members.get(i).getId().equals(id)){
				members.remove(i);
				found = true;
			}
		}
		if (!found) returnMessage = "Team doesn't contain member with id:\t"+id+"."+"\n";
		return returnMessage;
	}
	
	public synchronized boolean containsMember(User u){
		return this.getMembers().contains(u);
	}
	public synchronized boolean containsMember(String id){
		for(int i=0; i<getMembers().size(); i++){
			if(getMembers().get(i).getId().equals(id)){
				return true;
			}
		}
		return false;
	}

	public String[] getMemberIdsAsArray(){
		String[] ids = new String[getMembers().size()];
		for(int i=0; i<getMembers().size(); i++){
			ids[i] = getMembers().get(i).getId();
		}
		return ids;
	}
	
	public String getSummary(){
		StringWriter sw = new StringWriter();
		sw.append(getId());
		sw.append("[");
		for(int i=0; i<members.size(); i++){
			sw.append(members.get(i).getId()+" ");
		}
		sw.append("]");
		return sw.toString();
	}
	
	public Element toElement(){
		Element chatroom = new Element("chatroom");
		chatroom.setAttribute("id", getId());
		for(int i=0; i<getMembers().size(); i++){
			Element user = getMembers().get(i).toElement();
			chatroom.addContent(user);
		}
		return chatroom;
	}
	
	@SuppressWarnings("unchecked")
	public static Chatroom fromElement(Element eChatroom){
		Chatroom chatroom = new Chatroom();
		chatroom.setId(eChatroom.getAttributeValue("id"));
		List<Element> eUsers = eChatroom.getChildren();
		for(int i=0; i<eUsers.size(); i++){
			User user = User.fromElement(eUsers.get(i));
			chatroom.addMember(user);
		}
		return chatroom;
	}

}
